package com.vgemv.jsutilitysdk.InputBar;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.vgemv.jsutilitysdk.InputBar.JsInputBox.JsInputBoxBet;
import com.vgemv.jsutilitysdk.InputBar.JsInputBox.JsInputBoxCallback;
import com.vgemv.jsutilitysdk.JsButton.JsButton;
import com.vgemv.jsutilitysdk.JsKeyboardManager.JsKeyboardManager;
import com.vgemv.jsutilitysdk.JsThread.JsThreadManager;
import com.vgemv.jsutilitysdk.R;

public class JsBottomInputBarBet extends Fragment {

    private LinearLayout mll_root;
    public JsBottomInputBarBetaCallback mCallback;
    public JsBottomInputBarBetaVm mVm;

    public TextView met;
    public View mv_separator;
    public ImageView miv_pick;
    public ImageView miv_share;
    public JsButton miv_like;
    public TextView mtv_lickCount;

    public LinearLayout mll_mask;
    public JsInputBoxBet mInputBox;

    public Activity mActivity;

    private int setupUiCount;

    private ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(mCallback != null) {
            mVm = mCallback.jsBottomInputBarBetaSetVm(this);
        }
        if(mVm == null) {
            mVm = new JsBottomInputBarBetaVm();
        }
    }

    public void setupUiIfNeeded() {
        setupUiCount++;
        if(setupUiCount == 1) {
            JsThreadManager.runInMainThreadAtNextRunloop(new Runnable() {
                @Override
                public void run() {
                    setupUi();
                }
            });

        }
    }

    private void setupUi() {
        setupUi(mVm);
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //1 create,id,add
        mll_root = new LinearLayout(getContext());
        mll_root.setOrientation(LinearLayout.HORIZONTAL);
        mll_root.setId(View.generateViewId());
        mll_root.setGravity(Gravity.CENTER);
        setupUi(mVm);

        return mll_root;
    }

    public void setupUi(JsBottomInputBarBetaVm vm) {
        Context context = getContext();

        if(vm.mi_barBackgroundColor != null) {
            mll_root.setBackgroundColor(vm.mi_barBackgroundColor);
//            mll_root.setBackgroundColor(Color.argb(255,200,100,100));
        }

        //met
        {
            if(met == null) {
                met = new TextView(context);
                mll_root.addView(met);
                met.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT);
//                met.setTextAlignment(Tex);
                met.setMaxLines(1);
                met.setOnClickListener(new View.OnClickListener() {
                    @Override
                    //点击评论
                    public void onClick(View view) {
                        activateInputBox();
                    }
                });
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(JsBottomInputBarBetaVm.editTextWidth,JsBottomInputBarBetaVm.editTextHeight);
            lp.setMargins(JsBottomInputBarBetaVm.hPadding, 0,JsBottomInputBarBetaVm.hPadding,0);
            met.setLayoutParams(lp);
            met.setTextColor(mVm.mi_textColor);
            met.setPadding(30,0,30,0);
            met.setTextSize(mVm.mi_textSize);
            if(vm.mi_editTextBackgroundColor != null) {
                met.setBackgroundColor(vm.mi_editTextBackgroundColor);
            }

            String text = mVm.mstr_text;
            if(text.length() > 0) {
                SpannableString ss = new SpannableString(String.format("[草稿]%s", text));
                ss.setSpan(new ForegroundColorSpan(mVm.mi_textColor), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                met.setText(ss);
            }
            else {
                met.setText("写评论...");
            }
        }

        //separator
        {
            if(mv_separator == null) {
                mv_separator = new View(context);
                mll_root.addView(mv_separator);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(JsBottomInputBarBetaVm.separatorWidth,JsBottomInputBarBetaVm.editTextHeight);
            lp.setMargins(0, 0,JsBottomInputBarBetaVm.itemSpacing,0);
            mv_separator.setLayoutParams(lp);

            if(vm.mi_separatorBackgroundColor != null) {
                mv_separator.setBackgroundColor(vm.mi_separatorBackgroundColor);
            }
        }

        //picker
        {
            if(miv_pick == null) {
                miv_pick = new ImageView(context);
                mll_root.addView(miv_pick);

                miv_pick.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(mCallback != null) {
                            mCallback.jsBottomInputBarClickPick(JsBottomInputBarBet.this);
                        }
                    }
                });
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(JsBottomInputBarBetaVm.imageSize-12,JsBottomInputBarBetaVm.imageSize-12);
            lp.setMargins(0,0,JsBottomInputBarBetaVm.itemSpacing,0);
            miv_pick.setLayoutParams(lp);


            if(mVm.isPicked) {
                miv_pick.setImageResource(R.mipmap.star_yellow);
            }
            else {
                miv_pick.setImageResource(R.mipmap.star_gray);
            }
            if(vm.mi_buttonBackgroundColor != null) {
                miv_pick.setBackgroundColor(vm.mi_buttonBackgroundColor);
            }
        }

        //share
        {
            if (miv_share == null) {
                miv_share = new ImageView(context);
                mll_root.addView(miv_share);

                miv_share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(mCallback != null) {
                            mCallback.jsBottomInputBarClickShare(JsBottomInputBarBet.this);
                        }
                    }
                });
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(JsBottomInputBarBetaVm.imageSize-5, JsBottomInputBarBetaVm.imageSize-5);
            lp.setMargins(0, 0, JsBottomInputBarBetaVm.itemSpacing, 0);
            miv_share.setLayoutParams(lp);

            miv_share.setImageResource(R.mipmap.share_green);
            if(vm.mi_buttonBackgroundColor != null) {
                miv_share.setBackgroundColor(vm.mi_buttonBackgroundColor);
            }


        }

        //like
        {
            if(miv_like == null) {
                miv_like = new JsButton(context);
                miv_like.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(mCallback != null) {
                            mCallback.jsBottomInputBarClickLike(JsBottomInputBarBet.this,miv_like);
                        }
                    }
                });
                mll_root.addView(miv_like);

                //设置不变的属性
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(JsBottomInputBarBetaVm.imageSize,JsBottomInputBarBetaVm.likeHeight);
                lp.setMargins(0,(JsBottomInputBarBetaVm.likeHeight - JsBottomInputBarBetaVm.imageSize)/2,JsBottomInputBarBetaVm.itemSpacing,0);
                miv_like.setLayoutParams(lp);
                miv_like.mVm.mi_imageWidth = JsBottomInputBarBetaVm.imageSize;;
                miv_like.mVm.mi_imageHeight = JsBottomInputBarBetaVm.imageSize;
                miv_like.mVm.mi_textWidth = JsBottomInputBarBetaVm.imageSize;
                miv_like.mVm.mi_textHeight = JsBottomInputBarBetaVm.likeHeight - JsBottomInputBarBetaVm.imageSize;
                miv_like.mVm.mi_textY = miv_like.mVm.mi_imageHeight;
                miv_like.mVm.mi_textSize = 10;
                miv_like.mVm.mI_borderWidth = 0;
            }

            //设置变化值.
            miv_like.mVm.text = String.format("%d",mVm.likeCount);
            if(mVm.isLiked) {
                miv_like.mVm.mI_imageId = (R.mipmap.like_red);
                miv_like.mVm.mi_textColor = JsBottomInputBarBetaVm.mi_likeColor;
            }
            else {
                miv_like.mVm.mI_imageId = (R.mipmap.like_gray);
                miv_like.mVm.mi_textColor = JsBottomInputBarBetaVm.mi_unlikeColor;
            }
            miv_like.setupUiIfNeeded();
        }


        {
            //mll_mask MaskView
            if(mll_mask == null) {
                mll_mask = new LinearLayout(context);
                mll_mask.setId(View.generateViewId());
                mll_mask.setBackgroundColor(mVm.mi_maskColor);

                mll_mask.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //点击取消,保存草稿
                        deactivateInputBox();

                    }
                });

                mll_mask.setOrientation(LinearLayout.VERTICAL);
                mll_mask.setGravity(Gravity.BOTTOM);
            }

            //JsInputBoxBet
            if(mInputBox == null) {
                mInputBox = new JsInputBoxBet(context);
                mll_mask.addView(mInputBox);
                mInputBox.mCallback = new JsInputBoxCallback() {
                    @Override
                    //发布内容
                    public void jsInputBoxClickPublish(JsInputBoxBet inputBox, String text) {
                        if(mCallback != null) {
                            mCallback.jsInputBoxPublish(JsBottomInputBarBet.this,text);
                        }
                        //清除内容
                        inputBox.clear();
                        deactivateInputBox();
                    }
                };
            }

        }
        setupUiCount = 0;
    }
    // 3 Interface

    /**
     * 将当前fragment的rootView添加到指定的ContainerView中.
     * 这里设置会是占满ContainerView.
     * @param activity  指定的Activity
     * @param containerView      目标ContainerView
     */
    public void moveToParentView(AppCompatActivity activity, View containerView){
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(containerView.getId(),this);
        fragmentTransaction.show(this);
        fragmentTransaction.commit();
        mActivity = activity;
    }

//    public static WindowManager getActivityWindow(Activity activity) {
//        WindowManager windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
//        return windowManager;
//    }

    public void displayViewInActivityWindowManager(View view) {
        WindowManager windowManager = (WindowManager)mActivity.getSystemService(Context.WINDOW_SERVICE);
        //GaMark: Window的LayoutParam这里传入的不是宽高.
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

        //window的内容对齐方式
        lp.gravity = Gravity.BOTTOM;

        //设置要添加的View的大小
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;;

        //窗口设置为透明,默认不透明,为深黑色
        lp.alpha = 0.3f;
        lp.format = PixelFormat.TRANSLUCENT;

        lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        lp.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;

        int type = lp.type;
//        lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
//        addWindowFlags(WindowManager.LayoutParams.TYPE_STATUS_BAR);

        windowManager.addView(view,lp);

//        met_float.requestFocus();
    }

    public void displayViewInPhoneWindow(View view) {
        //GaMark PhoneWindow没有移除view的方法??
        Window window = mActivity.getWindow();
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        if(mll_mask.getParent() == null) {
            //GaMark,addContentView,类似于FrameLayout.addView();
            window.addContentView(mll_mask, lp);

            mInputBox.setupUiIfNeeded();
        }
    }

    public void activateInputBox() {
        addKeyboardObserver();
        displayViewInPhoneWindow(mll_mask);
        JsKeyboardManager.showKeyboard(mInputBox.met,getContext());
    }

    public void deactivateInputBox() {
        removeKeyboardObserver();
        undisplayViewFromPhoneWindow(mInputBox);
        mVm.mstr_text = mInputBox.mInputBoxBetVm.text;
        mInputBox.met.clearFocus();
        JsKeyboardManager.hideKeyboard(mActivity);
        setupUiIfNeeded();
    }

    public void undisplayViewFromPhoneWindow(View view) {
        Window window = mActivity.getWindow();
        //这个vp实质上是一个FrameLayout;
        ViewParent vp = mll_mask.getParent();
        FrameLayout fl = (FrameLayout)vp;
        fl.removeView(mll_mask);
    }

    public void displayViewInPhoneWindowManager(View view) {
        //GaMark PhoneWindow没有移除view的方法??
        Window window = mActivity.getWindow();
        WindowManager windowManager = window.getWindowManager();
//        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

        //window的内容对齐方式
        lp.gravity = Gravity.BOTTOM;

        //设置要添加的View的大小
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;

        if(mll_mask.getParent() == null) {
            windowManager.addView(mll_mask, lp);
        }
    }

    public void undisplayViewFromPhoneWindowManager(View view) {
        Window window = mActivity.getWindow();
        WindowManager windowManager = window.getWindowManager();
        windowManager.removeView(view);
    }

    public void removeKeyboardObserver() {
        final View rootView = mActivity.getWindow().getDecorView().findViewById(android.R.id.content);
        rootView.getViewTreeObserver().removeOnGlobalLayoutListener(mGlobalLayoutListener);
    }

    public void addKeyboardObserver() {
        //rootView为其中的conent?   //这个为什么一直在调用???
        final View rootView = mActivity.getWindow().getDecorView().findViewById(android.R.id.content);
        if(mGlobalLayoutListener == null) {
            mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect r1 = new Rect();
                    Rect r2 = new Rect();
                    //获取当前窗口实际的可见区域

                    //1794,没有包含状态栏.
//                    int screenHeight = JsGeometryManager.getDevicePixelSize().getHeight();

                    //JsGeometryManager.getDevicePixelSize().getHeight() = 1794.
                    //contentView-getWindowVisibleDisplayFrame --> (0,63 - 1080,1794) 表示contentView在window的区域是这个.后面的那个点是有下家的坐标,而不是高度.
                    //conentView.getBottom = 1731, getTop = 0,是自身的坐标系.
                    //contentView.getGlobalVisibleRect (0,0,1080,1794), 感觉这个是真真的手机全屏的尺寸.

                    //decorView-getWindowVisibleDisplayFrame --> (0,63 - 1080,1794)
                    //decorView,top:0,bottom:1920. decorView的bottom是1920,怎么这么多???

                    rootView.getWindowVisibleDisplayFrame(r1);
                    //getDrawingRect getLocalVisibleRect
                    //getHitRect getGlobalVisibleRect
                    rootView.getGlobalVisibleRect(r2);
//                JsLogManager.logc_d("xx","display frame,top:%d,bottom:%d,height:%d",r.top,r.bottom,r.height());
//                JsLogManager.logc_d("xx","root view,top:%d,bottom:%d,height:%d",rootView.getTop(),rootView.getBottom(),rootView.getHeight());
                    int raiseHeight = r2.bottom - r1.bottom;

                    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mInputBox.getLayoutParams();
                    lp.setMargins(0, 0, 0, raiseHeight);
                    mInputBox.setLayoutParams(lp);

                }
            };
        }
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);
    }

    //收藏
    public void pick() {
        mVm.isPicked = true;
        setupUiIfNeeded();
    }
    //取消收藏.
    public void unpick() {
        mVm.isPicked = false;
        setupUiIfNeeded();
    }
    public boolean isPicked() {
        return mVm.isPicked;
    }

    public boolean isLiked() {
        return mVm.isLiked;
    }

    public void like() {
        mVm.isLiked = true;
        setupUiIfNeeded();
    }
    public void unlike() {
        mVm.isLiked = false;
        setupUiIfNeeded();
    }
    //点赞数+1,并显示为点赞状态
    public void oneMoreLike() {
        mVm.isLiked = true;
        mVm.likeCount ++;
        setupUiIfNeeded();
    }
    //设置点赞数
    public void setLikeCount(int likeCount) {
        mVm.likeCount = likeCount;
        setupUiIfNeeded();
    }
}
